package it.polimi.swimv2.session;

import it.polimi.swimv2.entities.User;
import it.polimi.swimv2.remote.FriendsManagerRemote;

import java.util.ArrayList;
import java.util.Collection;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * Session Bean implementation class FriendsManager
 */
@Stateless
public class FriendsManager implements FriendsManagerRemote, FriendsManagerLocal {
	@PersistenceContext(unitName = "swimv2")
	EntityManager em;

	/**
	 * Default constructor.
	 */
	public FriendsManager() {

	}

	
	@SuppressWarnings("unchecked")
	@Override
	public Collection<User> getFriendsOf(String username) {
		User u = null;
		if (username != null) {
			u = em.find(User.class, username);
		}
		Collection<User> result = new ArrayList<User>();
		if (u != null) {
			Query q=em.createQuery("SELECT OBJECT(u) " +
					"FROM User u WHERE u.username IN " +
					"(SELECT fr.friend FROM Friendship fr WHERE fr.user= :u)");
			q.setParameter("u", u);
			result.addAll(q.getResultList());
		}
		return result;
	}

	@Override
	public boolean removeFriendship(String username1, String username2) {

		if (username1 == null || username2 == null) {
			return false;
		}

		User u1 = em.find(User.class, username1);
		User u2 = em.find(User.class, username2);

		if (u1 != null && u2 != null) {
			removeFriendship(u1,u2);
			removeFriendship(u2,u1);
			em.flush();
			return true;
		} else {
			return false;
		}
	}
	
	private void removeFriendship(User from, User who){
		Query q=em.createQuery("DELETE FROM Friendship fr WHERE fr.user = :from AND fr.friend = :who");
		q.setParameter("from", from);
		q.setParameter("who", who);
		q.executeUpdate();
	}


	@Override
	public boolean areFriends(User u1, User u2) {
		if(u1==null||u2==null){
			return false;
		}
		Query q=em.createQuery("SELECT fr FROM Friendship fr WHERE fr.user= :u1 AND fr.friend= :u2");
		q.setParameter("u1", u1);
		q.setParameter("u2", u2);
		if(q.getResultList().isEmpty()){
			return false;
		}else{
			return true;
		}
	}
}
